package org.nanotek.tika.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.tika.io.TemporaryResources;
import org.apache.tika.io.TikaInputStream;
import org.nanotek.Base;
import org.nanotek.tika.Detector;
import org.nanotek.tika.MediaDetail;
import org.nanotek.tika.MediaDetectionException;
import org.nanotek.tika.io.TikaMediaDetector;
import org.nanotek.tika.job.reader.DetectionException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class TikaMediaDetailDetector implements Detector <MediaDetail,Base<?>> , ApplicationContextAware{

private Logger log = Logger.getLogger(TikaMediaDetailDetector.class);
private ApplicationContext applicationContext;

	@Override
	public synchronized MediaDetail detect(Base<?> ref)  throws DetectionException {
		MediaDetail mediaDetail = null;
		TikaInputStream input = null;
		try {
			TemporaryResources tmp = new TemporaryResources();
			String fileLocation = (String) ref.getId();
			File refFile = new File(fileLocation); 
			if (!refFile.isDirectory()){ 
				input = TikaInputStream.get(new FileInputStream(fileLocation), tmp);
				TikaMediaDetector tikaMediaDetector = (TikaMediaDetector) applicationContext.getBean("tikaMediaDetector");
				mediaDetail = tikaMediaDetector.detectMediaType(input);
				mediaDetail.setLocation(fileLocation);
			} 
		} catch (IOException  | MediaDetectionException ex) 
		{ 
			ex.printStackTrace();
			log.debug( "Exception on Detection " + ex);
			throw new DetectionException(ex);
		}finally { 
			if (null != input) 
			{ 
				try {
					input.close();
					log.debug( "Closing File");
				} catch (IOException e) {
					e.printStackTrace();
					log.debug(e);
				}
			}
		}
		return  mediaDetail;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext; 
	}

}
